import time
from threading import Thread

from flask import request
from flask_jwt import jwt_required
from flask_restful import Resource
from qiniu import Auth, put_file

from common.crawlUtil import crawl_tmall, crawl_jd, crawl_1688
from common.db import KeywordData, UrlList


class AddKeyword(Resource):
    @staticmethod
    @jwt_required()
    def post():
        from run import session
        product = request.json.get('product')
        keyword = product.get('keyword')
        urlList = product.get('urlList')
        profit = product.get('profit')
        origin_price = product.get('origin_price')
        purchase_url = product.get('purchase_url')
        if keyword is None or urlList is None:
            return {"status": False, "msg": "参数错误"}
        if session.query(KeywordData).filter_by(keyword=keyword).first() is not None:
            return {"status": False, "msg": "商品已存在"}
        keywordData = KeywordData()
        keywordData.keyword = keyword
        keywordData.profit = profit
        keywordData.add_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        keywordData.average_origin_price = origin_price
        keywordData.purchase_url = purchase_url
        session.add(keywordData)
        try:
            session.commit()
        except:
            session.rollback()
        urllists = []
        for url in urlList:
            link = url.get("link")
            url_list = UrlList()
            url_list.keyword = keyword
            url_list.url = link
            url_list.add_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            if "detail.tmall.com" in link or "item.jd.com" in link:
                urllists.append(url_list)
            else:
                return {"status": False, "msg": "商品链接必须是天猫或京东"}
        session.add_all(urllists)
        session.commit()
        from run import calculate
        calculate.delay()
        return {"status": True, "msg": "添加成功"}


class DeleteKeyword(Resource):
    @staticmethod
    @jwt_required()
    def post():
        keyword = request.json.get('keyword')
        from run import session
        key = session.query(KeywordData).filter_by(keyword=keyword).first()
        session.delete(key)
        try:
            session.commit()
        except:
            session.rollback()
        return {"status": True, "msg": "删除成功"}


class Refresh(Resource):
    @staticmethod
    # @jwt_required()
    def get():
        from run import calculate
        calculate.delay()
        return {"status": True, "msg": "刷新成功"}


class GetUrl(Resource):
    @staticmethod
    @jwt_required()
    def post():
        keyword = request.json.get('keyword')
        from run import session
        url_lists = session.query(UrlList).filter_by(keyword=keyword).all()
        data = []
        for url in url_lists:
            data.append(url.to_json())
        return {"status": True, "data": data, "msg": "获取成功"}


class UpdateUrl(Resource):
    @staticmethod
    @jwt_required()
    def post():
        url = request.json.get("url")
        id = url.get("id")
        link = url.get("url")
        from run import session
        url_list = session.query(UrlList).filter_by(id=id).first()
        if "detail.tmall.com" in link:
            t = Thread(target=crawl_tmall(url_list))
            t.start()
        elif "item.jd.com" in link:
            t = Thread(target=crawl_jd(url_list))
            t.start()
        elif "detail.1688.com" in link:
            t = Thread(target=crawl_1688(url_list))
            t.start()
        else:
            return {"status": False, "msg": "商品链接必须是淘宝、京东或1688的"}
        return {"status": True, "msg": "更新成功"}


class DeleteUrl(Resource):
    @staticmethod
    @jwt_required()
    def post():
        print(request.json)
        id = request.json.get("id")
        from run import session
        url_list = session.query(UrlList).filter_by(id=id).first()
        session.delete(url_list)
        try:
            session.commit()
        except:
            session.rollback()
        return {"status": True, "msg": "删除成功"}


class UploadImage(Resource):
    @staticmethod
    def post():
        if 'img' in request.files:
            from run import photos, accessKey, secretKey, session
            filename = photos.save(request.files['img'])
            keyword = request.form.get("keyword")
            q = Auth(accessKey, secretKey)
            bucket_name = 'tandi-web'
            token = q.upload_token(bucket_name, filename, 3600)
            localFile = "img/" + filename
            ret, info = put_file(token, filename, localFile)
            print(info)
            keywordData = session.query(KeywordData).filter_by(keyword=keyword).first()
            keywordData.img_name = filename
            session.add(keywordData)
            try:
                session.commit()
            except:
                session.rollback()
            return {"status": True, "msg": "上传成功"}
        else:
            return {"status": False, "msg": "参数错误"}
